//
//  AttestServiceViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/30.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "AttestServiceViewController.h"
#import "PhotoSheetView.h"
#import "UICustomActionSheet.h"
#import "STActionSheet.h"
#import "DZNPhotoEditorViewController.h"
#import "UIImagePickerController+Edit.h"
#import "UIImageView+WebCache.h"
#import <UIImageView+RJLoader.h>
#import "PhotoPopView.h"

@interface AttestServiceViewController ()<UITextViewDelegate>
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroview;
@property (strong, nonatomic) IBOutlet UIButton *changeTypeButton;
@property (strong, nonatomic) IBOutlet UIButton *returnTypeButton;
@property (strong, nonatomic) IBOutlet UIButton *fixTypeButton;
@property (strong, nonatomic) IBOutlet UIButton *addphotoButton;
@property (strong, nonatomic) IBOutlet UITextView *textview;
@property (strong, nonatomic) IBOutlet UILabel *placeHolder;
@property(nonatomic,strong)NSMutableDictionary * photoDic;
@property(nonatomic,assign)NSInteger  currentIndexpath;
@end

@implementation AttestServiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _currentIndexpath = 0;
    _photoDic = [NSMutableDictionary dictionary];
    // Do any additional setup after loading the view.
    [self initViewLayout];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroview];
    _scroview.contentSize = flexibleSize(CGSizeMake(0, 460), YES);
    _textview.delegate = self;
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
#pragma mark == 售后说明
- (IBAction)saleService:(id)sender {
    
}

#pragma mark == 申请类型
- (IBAction)serviceType:(UIButton *)sender {
    if (sender == _changeTypeButton) {
        _changeTypeButton.selected = YES;
        _returnTypeButton.selected = NO;
        _fixTypeButton.selected = NO;
        _changeTypeButton.layer.borderColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000].CGColor ;
        _changeTypeButton.layer.borderWidth = 1;
         _returnTypeButton.layer.borderWidth = 0;
        _fixTypeButton.layer.borderWidth = 0;

    }else if (sender == _returnTypeButton){
        _changeTypeButton.selected = NO;
        _returnTypeButton.selected = YES;
        _fixTypeButton.selected = NO;
        _returnTypeButton.layer.borderColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000].CGColor ;
        _changeTypeButton.layer.borderWidth = 0;
        _returnTypeButton.layer.borderWidth = 1;
        _fixTypeButton.layer.borderWidth = 0;
    }else{
        _changeTypeButton.selected = NO;
        _returnTypeButton.selected = NO;
        _fixTypeButton.selected = YES;
        _fixTypeButton.layer.borderColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000].CGColor ;
        _changeTypeButton.layer.borderWidth = 0;
        _returnTypeButton.layer.borderWidth = 0;
        _fixTypeButton.layer.borderWidth = 1;
    }
}

#pragma mark == 提交申请
- (IBAction)commitAttest:(id)sender {
    NSString * images = @"";
    if (_currentIndexpath==0) {
//        [dic setObject:@"" forKey:@"CommtImg"];
    }else{
        for (int i=0; i<_currentIndexpath+1; i++) {
            NSString * image = _photoDic[[NSString stringWithFormat:@",%d",i]];
            if (i==0) {
                image = _photoDic[[NSString stringWithFormat:@"%d",i]];
            }
            images = [images stringByAppendingString:image];
        }
//        [dic setObject:images forKey:@"CommtImg"];
    }
}

- (IBAction)addPhoto:(UIButton*)sender {
    if (_photoDic.allValues.count>=3) {
        UIAlertView * alterView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"图片不能超过三张" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alterView show];
        return;
    }
    
    
    PhotoPopView * photoPopView = [[PhotoPopView alloc]initWithcomplect:^(NSInteger index) {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    
                    imageButton.frame = flexibleFrame(CGRectMake(15+61*_currentIndexpath, 293, 60, 60), YES);
                    [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                    [_scroview addSubview:imageButton];
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    
                    imageButton.frame = flexibleFrame(CGRectMake(15+61*_currentIndexpath, 293, 60, 60), YES);
                    [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                    [_scroview addSubview:imageButton];
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
            
            
            
        }else {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    
                    imageButton.frame = flexibleFrame(CGRectMake(15+61*_currentIndexpath, 293, 60, 60), YES);
                    [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                    [_scroview addSubview:imageButton];
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIButton * imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    
                    imageButton.frame = flexibleFrame(CGRectMake(15+61*_currentIndexpath, 293, 60, 60), YES);
                    [imageButton setBackgroundImage:image forState:UIControlStateNormal];
                    [_scroview addSubview:imageButton];
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
        }
        
    }];
    [photoPopView show];
    
}


#pragma mark - 上传图片--------------------------
- (void) imageUpload:(int)numberImg:(UIImage *)imageImage{
    NSString *url = SX_uploadCommentImg;
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    //    UIImage *image=[params objectForKey:@"pic"];
    //得到图片的data
    CGSize newSize = CGSizeMake(50, 50);
    UIGraphicsBeginImageContext(newSize);
    [imageImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData* data  = UIImageJPEGRepresentation(newImage, 0.5);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //设置HTTPHeader中Content-Type的值
    NSString* content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    //    [body appendFormat:@"Content-Type: %@\r\n\r\n",content];
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *headerUserAgent=@"";
    if ([Common getLoginStatus]) {
        NSString *userName = [[Common getLoginInfo] objectForKey:Key_User_nickname];
        NSString *userId  = [NSString stringWithFormat:@"%@",[[Common getLoginInfo] objectForKey:Key_User_userId]];
        NSString *encryptPwd  = [Common shaEncrypt:[[Common getLoginInfo] objectForKey:Key_User_password]];
        NSString *localUserIdentify  = [[UIDevice currentDevice].identifierForVendor UUIDString];
        headerUserAgent = [NSString stringWithFormat:@"%@|%@|%@|%@",userName,userId,encryptPwd,localUserIdentify];
    }else{
        headerUserAgent = @"|||";
    }
    
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置User-Agent
    [request setValue:headerUserAgent forHTTPHeaderField:@"User-Agent"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    //建立连接，设置代理
    //    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    //上传文件开始
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //获得返回值
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSMutableDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
    
    //取得返回的图片名
    //    NSArray* array = [returnString componentsSeparatedByString:@"###"];
    NSString * image = [NSString stringWithFormat:@"%@", dictionary[@"result"][0][@"simaId"]];
    
    [_photoDic setObject:image forKey:[NSString stringWithFormat:@"%ld",_currentIndexpath]];
    _currentIndexpath +=1;
    _addphotoButton.frame = flexibleFrame(CGRectMake(15+61*_currentIndexpath, 293, 60, 60), YES);
    
    
    
}


- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    _placeHolder.hidden = YES;
    
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    if (_textview.text.length>0) {
        _placeHolder.hidden = YES;
    }else{
        _placeHolder.hidden = NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
